﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace ASPItalia.ModelVirtualCasting.Web
{
	public partial class UploadImage : System.Web.UI.Page
	{
		private void Page_Load(object sender, System.EventArgs e)
		{
			string physicalApplicationPath = HttpContext.Current.Request.PhysicalApplicationPath;

			if (Request.QueryString["total"] != null &&
				Request.QueryString["current"] != null &&
				Request.QueryString["filename"] != null)
			{
				int current = Convert.ToInt32(Request.QueryString["current"]);
				int total = Convert.ToInt32(Request.QueryString["total"]);
				string filename = Convert.ToString(Request.QueryString["filename"]);
				filename = HttpUtility.HtmlDecode(filename);

				string path = "Images";

				string filePath = String.Format("{0}\\{1}\\{2}", physicalApplicationPath, path, filename);

				int bufferLenght = (int)Request.InputStream.Length;
				byte[] buffer = new byte[bufferLenght];
				Request.InputStream.Read(buffer, 0, bufferLenght);

				if (current == 1)
				{
					using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write))
					{
						fileStream.Write(buffer, 0, bufferLenght);
					}
				}
				else
				{
					using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Write))
					{
						fileStream.Write(buffer, 0, bufferLenght);
					}
				}

				Response.Clear();
				Response.End();
			}
			else
			{
				Response.Clear();
				Response.Write("error");
				Response.End();
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion
	}
}